package com.seahorse.youliao.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.seahorse.youliao.common.ResponseCode;
import com.seahorse.youliao.common.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.security
 * @ClassName: AuthenticationEntryPoint
 * @Description: 身份认证处理
 * @author:songqiang
 * @Date:2020-11-25 16:21
 **/
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        ResponseEntity respBean = new ResponseEntity();
        respBean.setCode(ResponseCode.TOKEN_INVALID.getCode());
        respBean.setRemark("认证异常:"+ exception.getMessage());
        //封装异常描述信息
        String json = JSONObject.toJSONString(respBean);
        out.write(json);
        out.flush();
        out.close();
    }
}
